<?php 
///////////
///////////  todo:  ADD SOCAN FIELDS TO JS VALIDATION
///////////

session_start();

$user = $_SESSION['password'];
if (!$user) { header('location: login.php'); exit; }

include "../includes/functions.php";
echo db_connect();
//date_default_timezone_set ("America/Vancouver");

 //print_r($_POST);

$show_id = $_GET['show_id']; if (!$show_id) $show_id = $_POST['show_id']; if (!$show_id) { header("location: playlists.php"); exit; }

$playlist_id = $_GET['playlist_id'];
$new_date = $_POST['new_date']." 00:00:00";   

if ($_GET['mode'] ==  "edit")  {
	
	$edit_item = $_GET['item_id'];	
}



if ($_POST['delete']) {
$del_id = $_POST['delete'];
$del_query = 'DELETE FROM playlist_items WHERE playlist_item_id = "'.$del_id.'"'; //echo $del_query; exit;
$del_result = mysql_query($del_query); if (!$del_result){ $msg = " ERROR deleting pl";} else { $msg = " Track deleted successfuly";}

}

if ($_POST['post'])  {   ///    new entry submitted

	//print_r($_POST);
	
	$playlist_id = $_POST['playlist_id'];
	$toadd_song_title = $_POST['song_title'];
	$toadd_category = $_POST['category'];
	$toadd_id = $_POST['testid'];
	
	
	
	if (!$toadd_id) {
			$ml_select = 'SELECT album_id FROM ml_albums WHERE artist = "'.$_POST['dataa'].'" AND title = "'.$_POST['album'].'"';
			$ml_result = mysql_query ($ml_select); if (!$ml_result) die(mysql_error().$ml_select);
			if ($ml_row = mysql_fetch_array($ml_result)) {
			 $toadd_id = $ml_row['album_id'];  
			} else {
			  $toadd_id = ""; 
			}
	}
	
	$lookup_query = 'select artist, title, label, section_id from ml_albums where album_id = "'.$toadd_id.'"';
	$lookup_result = mysql_query($lookup_query);
	$lookup_row = mysql_fetch_array($lookup_result);
	$toadd_album = $lookup_row['title'];
	$toadd_artist = $lookup_row['artist'];
	$toadd_label = $lookup_row['label'];
	$toadd_section_id = $lookup_row['section_id'];
	
	///  SOCAN
	$toadd_duration = $_POST['duration_minutes'];
	$socan_time_played = $_POST['socan_time_played'];
	$toadd_composer = $_POST['composer'];
	$toadd_theme_bg = $_POST['theme_bg'];
	
	if (!$toadd_id) { // no link to a library album - use posted data
		$toadd_album = $_POST['album'];
		$toadd_artist = $_POST['dataa'];
		$toadd_playbox_p = $_POST['playbox_p'];
		$toadd_cancon_p = $_POST['cancon_p'];
		$toadd_section_id = $_POST['ml_section_id'];
		if (!$toadd_label) $toadd_label = $_POST['label'];
	}  
	
	//echo "debug taaddlabel $toadd_label";  
	
	$edit_id = $_POST['edit'];
	
	if ($edit_id) {
	  
	$query = 'UPDATE playlist_items SET 
	   artist = "'.$toadd_artist.'", 
	   album="'.$toadd_album.'", 
	   label = "'.$toadd_label.'", 
	   playlist_id= "'.$playlist_id.'", 
	   track_name = "'.$toadd_song_title.'", 
	   ml_album_id = "'.$toadd_id.'", 
	   playbox = "'.$toadd_playbox_p.'", 
	   cancon = "'.$toadd_cancon_p.'", 
	   category ="'.$toadd_category.'",
	   
	   composer ="'.$toadd_composer.'",
	   theme_bg ="'.$toadd_theme_bg.'",
	   duration_minutes ="'.$toadd_duration.'",
	   socan_time_played ="'.$socan_time_played.'",
	 
	   ml_section_id="'.$toadd_section_id.'" 
	WHERE playlist_item_id = "'.$edit_id.'"';	
	//performer ="'.$toadd_performer.'",
	//echo $query; exit;
		
	} else { 
		
	if (!$playlist_id) {
		$playlist_date_lookup = $new_date;
	 }else{
		$playlist_date_result = mysql_query("SELECT datetime FROM playlists WHERE playlist_id = '$playlist_id'");
		$playlist_lk_row=mysql_fetch_array($playlist_date_result); 
		$playlist_date_lookup = $playlist_lk_row[0];
	 }	
	 
	
	$query = 'INSERT INTO playlist_items VALUES ("","'.$toadd_artist.'","'.$toadd_album.'","'. $toadd_composer .'","","'.$playlist_date_lookup.'","'.$toadd_duration.'","'.$toadd_label.'","'.$playlist_id.'","'.$toadd_song_title.'","'.$toadd_id.'","'.$toadd_playbox_p.'","'.$toadd_cancon_p.'","","'.$toadd_category.'","'.$toadd_theme_bg.'","'.$toadd_section_id.'","'.$socan_time_played.'")';
	
	}
	
	//echo $query;
	
	$result = mysql_query($query); if (!$result) { echo "error creating new entry: $query;"; exit; }

}


if (!$playlist_id) {  /// make a new playlist entry for today (ADD) IF there isn't one already

	//$check_query = 'SELECT FROM playlists WHERE show_id = ".$show_id." AND `datetime` = NOW() ' 
	 
	//
	//  PULL OCCURRENCE ID BASED ON $new_date - if none for this day of the week, HALT PROCESS
	$oc_q = "SELECT id, start_time, end_time FROM show_occurrances WHERE show_id = '$show_id' AND day_of_week = '".date('l',strtotime($new_date))."'";
  // echo date('l',strtotime($new_date)); exit;
	$oc_r = mysql_query($oc_q);
	$oc_row = mysql_fetch_array($oc_r);
	$start_time = $oc_row['start_time']; $start_hour = substr($start_time,0,2); if ($start_hour > 12) $start_hour = $start_hour - 12;
	$end_time = $oc_row['end_time']; $end_hour = substr($end_time,0,2); if ($end_hour > 12) $end_hour = $end_hour - 12;
	$occurrance_id = $oc_row['id']; if (!$occurrance_id) DIE ("<html><script language='JavaScript'>alert('The show you chose does not occur on the chosen date. \\n\\nPlease check your entries and try again.'),history.go(-1)</script></html>"); 
	$show_occurrance_id = $occurrance_id;
	 
	// check if there is an existing plalist for this occ id today....
	$query='SELECT playlist_id FROM playlists WHERE show_occurrance_id = '.$occurrance_id.' AND datetime = "'.$new_date.'"';
	$result= mysql_query($query); if (!$result) { echo "ERROR Checking existing PLAYLIST: $query";exit;}
	$row= mysql_fetch_array($result);
	
	if (!$row[0]) {  // no existing playlist for today - make one
		
		//  SAVE OCURRENCE ID WITH PLAYLIST - WE WILL NEED IT

		$query='INSERT INTO playlists VALUES ("","'.$show_id.'","'.$new_date.'","1","'.$occurrance_id.'")';
		$result= mysql_query($query); if(!$result) {echo "ERROR CREATING PLAYLIST: $query";exit;}
		$playlist_id = mysql_insert_id();   
	
	} else { // no playlist id - return to playlists page
		header('location:playlists.php');
		exit;
		
	}
	
	
	
	
} else {

	$query='SELECT * FROM playlists WHERE show_id = '.$show_id.' AND playlist_id = "'.$playlist_id.'"';
	$result= mysql_query($query); if (!$result) { echo "ERROR SELECTING PLAYLIST: $query";exit;}
	
	$row= mysql_fetch_array($result); 
	$show_id = $row['show_id'];
	$show_occurrance_id = $row['show_occurrance_id'];
	$playlist_id = $row['playlist_id'];
	$datetime = $row['datetime'];

}

$show_query = 'select * from shows where show_id = "'.$show_id.'"';
$show_result= mysql_query($show_query);
$show_row= mysql_fetch_array($show_result);
$show_name = $show_row[1];

$item_query = 'select * from playlist_items where playlist_id = "'.$playlist_id.'" ORDER by playlist_item_id'; //echo $item_query;
$item_result= mysql_query($item_query);


if ($datetime){ $date = dateformat($datetime, '', $format = 1); $date_raw = $datetime; } else {$date = dateformat($new_date, '', 1); $date_raw = $new_date;}
 

# GET PAST 3 SHOWS FOR repeat DD
$repeat_dd = "<div class='prefill_container'>
Automatically fill this playlist from a past show<form name='repeat_dd' method='post' action='_prefill_playlist_items.php' onSubmit='return validateAutofill();'><input type='hidden' name = 'playlist_id' value='$playlist_id'><input type='hidden' name='show_id' value='$show_id'><select name='pl_id_to_copy' id='pl_id_to_copy'><option value=''>-- Choose past show ---</option>";

$dd_sql = "SELECT playlist_id, datetime FROM playlists WHERE show_id = '$show_id' ORDER BY datetime DESC LIMIT 7";
$dd_res = mysql_query($dd_sql);
while ($dd_row = mysql_fetch_array ($dd_res)) {
  $tracks_ct_res = mysql_query("SELECT COUNT(*) FROM playlist_items WHERE playlist_id = '".$dd_row[0]."'");
  $tracks_ct_row = mysql_fetch_array($tracks_ct_res); $tracks_ct = $tracks_ct_row[0];
	
 if ($dd_row[0] != $playlist_id && $tracks_ct_row[0] != 0) { $repeat_dd .= "<option value='".$dd_row[0]."'>".dateformat($dd_row[1],'',1) ." (".$tracks_ct_row[0]." tracks)</option>"; }  
}
$repeat_dd .= "</select> &nbsp;<input type='submit' name='submit' value='Fill Playlist'></form></div>";


///  GET SPONSORSHIP ITEMS

$schedule_query = 'select * from sponsorship_schedules where show_id = "'.$show_occurrance_id.'" and (datetime = "'.$date_raw.'" OR datetime = "0000-00-00 00:00:00") order by `sort`';
$schedule_result= mysql_query($schedule_query);  //echo $schedule_query;
while ($schedule_row= mysql_fetch_array($schedule_result))  {
	
	$schedule_id = $schedule_row['id'];
	$schedule_spot_id = $schedule_row[0];

	$spot_query = 'select * from sponsorship_spots where id = "'.$schedule_spot_id.'"';
	$spot_result= mysql_query($spot_query);
	
	$spot_row= mysql_fetch_array($spot_result);
	$spot_name = $spot_row[1];
	$spot_datetime = $schedule_row['datetime'];
	$spot_text = $spot_row['text'];
	$spot_track_num = $spot_row['track_number'];
	$spot_time_to_play = substr ($schedule_row['time_to_play'],0,5); 
	if ($schedule_row['time_to_play'] != "00:00:00") {$ttp = " (Play at $spot_time_to_play)";}else{$ttp="";}
	//print_r($schedule_row);
    $done_query = "SELECT * FROM schedules_done WHERE show_occurrance_id = '$show_occurrance_id' AND schedule_id = '$schedule_id'"; 
//echo $done_query;
    $done_result = mysql_query ($done_query); $done_row = mysql_fetch_array($done_result); ///print_r ($done_row);

if ($done_row[0]) {
	$time_done_arr = explode (":",$done_row['time_done']);  
	$class = "schedule_done"; $button_visibile = " display:none;";
	$tdid = $done_row[0];
	$td = $done_row[4];
	$end_javascript .= "$('#loading-$tdid').html('Done at $td&nbsp;&nbsp;&nbsp;'); $('#loading-$tdid').show();\n";
	$hidden_field = "<input id='time_minutes-$schedule_id' type='hidden' value='".$time_done_arr[1]."'><input id='time_hour-$schedule_id' type='hidden' value='".$time_done_arr[0]."'>";  
	} else { 
	$class = "index_table_empty";  $button_visibile = "";
	$hidden_field = ""; 
		}
if (substr ($spot_datetime,0,4) == "0000") {
	 $weekly_msg="&nbsp;&nbsp;(Plays every week for this show)";
	 $class = "index_table_repeating";
   }else{$weekly_msg="";}  
	
//$myURL = "playlist_new.php?show_id=$show_id&playlist_id=$playlist_id";

//<td width='25%'  onClick=\"window.location.href='$myURL'; \" ><a href='playlist_new.php?show_id=$show_id&playlist_id=$playlist_id'>xxx</a></td>

if ($spot_time_to_play != "00:00" ) { $ttp = "<div width='25px' style='padding: 2px; float:left;'>$spot_time_to_play</div>  "; } else { $ttp="<div style='padding: 2px; float:left; min-width:25px;'></div>";  }
if ($spot_text ) { $txt = "<div width='25' style='padding: 2px; float:left;margin-left:20px; font-weight:bold;' ><a href='#' title='$spot_text' onClick=\"showHidePopup('show','$spot_text');\" style='color:blue;'>Text to read (click to read)</a></div>  "; } else { $txt="";  }
if ($spot_track_num ) { $trn = "<div width='25' style='padding: 2px; float:left;margin-left:20px; font-weight:bold;color:blue;'>Play track # <span style='color:black; font-size: 14px;'>$spot_track_num</span> on Paddy</div>  "; } else { $trn="";  } 

if ($tp) {$copyLink = " <a onClick=\"copyFromAbove('$schedule_id');\"><img src='../images/button_copy_time.jpg' border='0' title='Copy time from the schedule above this one.'></a>";}else {$copyLink = "";}
$tp = 1;
$schedules .= "<div id = 'sch-$schedule_id' class = '$class' style='position:relative;height: 18px;margin-top: 4px;'>
	$ttp
	$hidden_field
	<div width='25' style='padding: 2px; float:left; font-size: 12px;'\">• $spot_name$weekly_msg</div>
	$txt$trn  
	<div width='25' class='done_button' id='doneButton-$schedule_id' style='$button_visibile' onClick=\"saveDoneSchedule($schedule_id, $show_occurrance_id); \"> Mark as DONE </div>
		<div width='25' class='time_played' id='timePlayed-$schedule_id' style='z-index:99;$button_visibile'> 
		Time done: <input type='text' maxlength='2' class='input_t' id='time_hour-$schedule_id' name='time_minutes-$schedule_id' value='$start_hour'> : 
		<input type='text' class='input_t' maxlength='2' id='time_minutes-$schedule_id' value='' name='time_minutes-$schedule_id'>$copyLink </div>
	<div width='25' class='' id='loading-$schedule_id' style='display:none; float:right;padding-top:2px;'> Saving... </div>
</div> ";

}
if (!$schedule_id) $schedules = "<span style='color:black;'> &nbsp;None</span>";

//  GET SECTIONS FOR DROP-DOWN

$s_result = mysql_query ("SELECT * FROM ml_sections");
while ($s_row = mysql_fetch_array($s_result)) {
	$sections_arr[$s_row[0]] = array ('section_label' => $s_row[1], 'section_image_tag'=>$s_row[2]); 
}


?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Playlist</title>
<link href="../css/text.css" rel="stylesheet" type="text/css" />
<link href="../css/style.css" rel="stylesheet" type="text/css" />
<style type="text/css"> . body { 	margin:0px;  } </style>
<script type="text/javascript" src="../autosuggest/js/bsn.AutoSuggest_for_playlist.js" charset="utf-8"></script>

<link rel="stylesheet" href="../autosuggest/css/autosuggest_inquisitor.css" type="text/css" media="screen" charset="utf-8" />

<style type="text/css" media="screen">
	.tdgreen {
		border-width: 0px 0px 0px 0px; 
	}
</style>


<script type="text/javascript">

function saveDoneSchedule(schedule_id, show_occurrance_id)  {
  var scheduleBox = '#sch-'+schedule_id;
  var doneButton = '#doneButton-'+schedule_id;
  var loading = '#loading-'+schedule_id;
  var td = $('#time_hour-'+schedule_id).val() + ':' + $('#time_minutes-'+schedule_id).val(); 
 if ($('#time_minutes-'+schedule_id).val() == '' || $('#time_hour-'+schedule_id).val() == '') {
	alert('Please enter the time you completed this item.');
 } else {

	$('#time_minutes-'+schedule_id).val()
	$(doneButton).hide(); $('#timePlayed-'+schedule_id).hide();   
	$(loading).show();
  // alert (loading);
   $.post("_save_done_schedule.php", {schedule_id: schedule_id, show_occurrance_id:show_occurrance_id, time_done:td} , function(data){
	//alert ('|'+data+'|');  
	if (data == '1') {
		
		$(scheduleBox).removeClass().addClass('schedule_done');
		$(loading).html('Done at '+td+'&nbsp;&nbsp;&nbsp;');
		
    } else {
	  	alert (data);
		$(loading).hide();
		$(doneButton).show();
		$('#timePlayed-'+schedule_id).show(); 
	}
	});

  } // end of if time not empty  
	
}

function copyFromAbove(schedID) {  // copy schedule time from the one above
	prevID = parseInt(schedID); prevID = prevID - 1;
	var x=$('#time_minutes-'+prevID).val();
	$('#time_minutes-'+schedID).val(x);
	var y=$('#time_hour-'+prevID).val();
	$('#time_hour-'+schedID).val(y); 
}

function MM_jumpMenu(targ,selObj,restore){ //v3.0
  eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
  if (restore) selObj.selectedIndex=0;
}

function clearField()
{
var fldVal = $('#testinput_xml').value();
//document.myform.dataa.value;
//alert (fldVal);
if (fldVal == " - Find by Artist, Keyword -") { 
	//document.myform.dataa.value = ""; 
	$('#testinput_xml').value(''); }
}
 
function fillField()
{
var fldVal = $('#testinput_xml').value();
//document.myform.dataa.value;
//alert (fldVal);
if (fldVal == "") {
	$('#testinput_xml').value(' - Find by Artist, Keyword -'); 
	//document.myform.dataa.value = " - Find by Artist, Keyword -"; 
	}
}

function validate(socan)  {
  
	//artist = document.additem.dataa.value;
	
	artist = $('#testinput_xml').val();
	album = document.additem.album.value;
	song = document.additem.song_title.value;
   	
	if (socan) { 
		composer = $('#composer').val();
		theme_bg = $('#theme_bg').val();
		duration_minutes = $('#duration_minutes').val();
		socan_time_played = $('#socan_time_played').val();
		
		    if (artist != "" && album != "" && song != "" &&  composer != "" && theme_bg != "" && duration_minutes != "" && socan_time_played.length > 3)  {

			   return true;

			} else {  

				if (document.additem.submit_via_button_flag.value !='')  {
				alert ('please fill out all of the blanks on the form correctly before adding this track');	
				}
			return false; 
			}
	} else { // not socan week 
		 if (artist != "" && album != "" && song != "")  {

		   // return true;

		} else {  

			if (document.additem.submit_via_button_flag.value !='')  {
			alert ('please fill out the Artist, Album and Song blanks before adding this album');	
			}
		return false; 
		}
		
	} // end if not socan week
   
}

function validateDel(id)  {
	if (confirm ("Are you sure you want to delete this track?") )  {
		return true;
	} else {  return false; }	
}

function validateAutofill() {
	if ($('#pl_id_to_copy').val() = '') { 
	 		alert('Please choose a past show before continuing.');
			} else {
			  	var date = $("#pl_id_to_copy :selected").text();
				if (confirm ("Are you sure you want to fill this playlist with tracks from the show on "+date+"?") )  {
					return true;
				} else {  return false; }
			}
	
}


</script>





</head>

<body bgcolor="#eeeeee" onLoad="$('#testinput_xml').focus();"><div class="container" style="padding:10px;">
<div id="bg_blanker" style="position:fixed; _position:absolute; top:-12px; left:0px; width:100%; height:100%; background-color:white;z-index:98;background-color: rgba(0, 0, 0, 0.7); display:none;"></div>
<script type="text/javascript" src="../wz_tooltip/wz_tooltip.js"></script>
<script type="text/javascript" src="../includes/jquery.js"></script>
<a href='playlists.php'><u>«PLAYLISTS</u></a> :: <span id='header' style='font-size:18px;'><?=$header_msg?> <strong><?=$show_name?></strong> on <strong><?=$date?> </strong></span>
<br /><br /><br /><?=$msg?> 
<div id="text_window" style="position:absolute; top:80px; left:150px; padding: 60px; width:500px; background-color:white;z-index:99;font-size:18px;display:none;">
<div style="position:absolute; top:5px; left:5px; background-color:gray;width:25px;text-align:center; color:white;" onClick="showHidePopup('hide','');">X</div>
<div id="text_window_container"></div>
</div>
<div id="sponsorships_container" style=" width:800; background-color:#656780;margin-bottom:30px;padding:4px;color:white;">
<strong>Scheduled Items for this Show:</strong>
<?=$schedules?>
</div>

<table width="100%" border="0" cellspacing="0" cellpadding="2">
  <tr>
   <td width="2" bgcolor="#666666"><strong><font color="#FFFFFF">&nbsp;</font></strong></td>
    <td width="20%" bgcolor="#666666"><strong><font color="#FFFFFF">Performer</font></strong></td>
    <td width="25%" bgcolor="#666666"><strong><font color="#FFFFFF">Album</font></strong></td>
    <td width="20%" bgcolor="#666666"><strong><font color="#FFFFFF">Song Title</font></strong></td>
    <td width="12%" bgcolor="#666666"><strong><font color="#FFFFFF">Label</font></strong></td>
    <td width="12%" bgcolor="#666666" colspan="2"><strong><font color="#FFFFFF"> </font></strong></td>
  </tr>
  
<?php 


$z=0;
while ($item_row= mysql_fetch_array($item_result)) {
	$arr[$z][id] = $item_row['playlist_item_id'];
	$arr[$z][album] = $item_row['album'];
	$arr[$z][artist] = $item_row['artist'];
	$arr[$z][composer] = $item_row['composer'];
	$arr[$z][label] = $item_row['label'];
	$arr[$z][track_name] = $item_row['track_name'];
  	$arr[$z][category] = $item_row['category'];
	$arr[$z][ml_album_id] = $item_row['ml_album_id'];
	$arr[$z][ml_section_id] = $item_row['ml_section_id'];
	
	$arr[$z][composer] = $item_row['composer'];
	$arr[$z][theme_bg] = $item_row['theme_bg'];
	$arr[$z][duration_minutes] = $item_row['duration_minutes'];
	$arr[$z][socan_time_played] = $item_row['socan_time_played'];
	
	$this_id = $item_row['ml_album_id']; //echo $this_id;
	
	/// GET THE GOODS ON THIS ALBUM FROM ML_ALBUMS;
	
	if ($this_id) { /// get cancon, status, category from album
		$item_album_query = 'SELECT cancon_p,playbox_p,section_id from ml_albums WHERE album_id = "'.$this_id.'"'; //echo"  $item_album_query"."<br>";
		$item_album_result = mysql_query($item_album_query);
		$item_album_row = mysql_fetch_array ($item_album_result); //echo">>>>>>>>>"; print_r($item_album_row);
		$cancon = $item_album_row['cancon_p']; 
		$playbox = $item_album_row['playbox_p'];
		$section_id = $item_album_row['section_id']; 
	} else {  /// get cancon, status, category from posted values
		$cancon = $item_row['cancon'];
		$playbox = $item_row['playbox'];
		$section_id =$arr[$z][ml_section_id];
	}
	
	if ($cancon == "Y") { $arr[$z][cancon] = "<font color = 'red'>Canadian</font>";}else{$arr[$z][cancon]="";}
	if ($playbox == "P") {$arr[$z][playbox] = "<font color = 'blue'>In Playbox</font>";
	} else if ($playbox == "L") {
		$arr[$z][playbox] = "<font color = 'green'>In Library</font>";
		} else if ($playbox == "B") {
			$arr[$z][playbox] = "<font color = 'green'>Downstairs<br> Archive</font>";
	} else {
		$arr[$z][playbox] = "";
	}
	
	# LOOKUP SECTION TITLE
	$lookup = mysql_query ("SELECT section_label FROM ml_sections WHERE section_id = '$section_id'");
	$llrow = mysql_fetch_array($lookup); 
	$arr[$z][section_label] = $llrow[0];
	
$z++;

}

if($z) $repeat_dd = "";  # DON'T SHOW AUTOFILL DD UNLESS ITS A BLANK PLAYLIST

//print_r($arr);

$order = 1;
 
 for ($i = 0; $i < $z ; $i ++)
 {
 if ($x == 1) { $x = 0; } else { $x = 1;} 
 if ($x == 1) { $bg = "#bbbbbb"; } else { $bg = "#dddddd"; }
  

	if ($edit_item && $arr[$i][id] == $edit_item) {  ///  is this one flagged for edit?
		 
		 $no_add = 1;
		 # showForm($playlist_id,$show_id,$i,$arr,$sections_arr);
		  showFormSOCAN($playlist_id,$show_id,$i,$arr,$sections_arr); 
	 } else {
	
		showListing ($arr,$show_id,$playlist_id,$bg,$order,$x,$i);
		showListingSOCAN ($arr,$show_id,$playlist_id,$bg,$order,$x,$i);  // turn off when not SOCAN week
	 }
	 
  
	$order ++;
	
	} // end of cycle thru existing items
	
# if (!$no_add) showForm($playlist_id,$show_id,$i,$arr,$sections_arr);
 if (!$no_add) showFormSOCAN($playlist_id,$show_id,$i,$arr,$sections_arr); 
  
?>


  
</table>
<br /><br /><input name="Done" type="button" value="Save Playlist" onClick="validateDone();"/>
<script type="text/javascript">
	var options = {
		script:"autosuggest/playlist_lookup.php?json=true&limit=6&",
		varname:"input",
		json:true,
		shownoresults:false,
		maxresults:12,
		callback: function (obj) {  }
	};
	var as_json = new bsn.AutoSuggest('testinput', options);
	
	
	var options_xml = {
		script: function (input) { return "autosuggest/playlist_lookup.php?input="+input+"&testid="+document.getElementById('testid').value; },
		varname:"input"
	};
	var as_xml = new bsn.AutoSuggest('testinput_xml', options_xml);

function showHidePopup(which, what) {
	if (which == 'show') {
	  	$('#text_window_container').html(what);
		$('#text_window').fadeIn('fast');
		$('#bg_blanker').fadeIn('fast');
		 
	} 
	
	if (which == 'hide') {
	  $('#text_window').fadeOut('fast');
	  $('#bg_blanker').fadeOut('fast');
	}
	
}

function validateDone() {
		
	if ($('#song_title').val() == "") {
		window.location = 'playlists.php';
	} else {
		alert ('Please click the Add button to add your current track to the list before saving the playlist.');
	}
} 

</script>
<br />

</div>
<script type='text/javascript'>
<?=$end_javascript?>
</script>
<br><br><br><br><br>

   <?=$repeat_dd?>


</body>
</html>









<?php
function showForm ($playlist_id,$show_id,$i,$arr,$sections_arr)  {
	/// BE SURE TO MIRROR ANY CHANGES TO THE FOLLOWING SOCAN FUNCTION
	$artist = $arr[$i][artist];
	$id = $arr[$i][id];
	//$category = $arr[$i][category]; if (!$category) $category = '2'; // default for blank 
	$section_id = $arr[$i][ml_section_id]; if (!$section_id || $section_id == 12) $section_id = 12;
	$cancon = $arr[$i][cancon]; if ($cancon) $cancon_check = "checked='checked'";
	$playbox = $arr[$i][playbox]; 
	if ($playbox == 'P') { $playbox_check = "checked='checked'"; } 
	if ($playbox == 'L') { $library_check = "checked='checked'"; }
	if ($playbox == 'B') { $downstairs_check = "checked='checked'"; }
	$label = $arr[$i][label];
	$track_name = $arr[$i][track_name];
	$album = $arr[$i][album];
	$album_id = $arr[$i][ml_album_id];
	
	if ($artist) { $button = "Save"; } else { $button = "Add"; }
	
	# BUILD SECTIONS drop-down
	$temp = "<select name='ml_section_id' class='small_inputs' style='background-color: green; color:white;' tabindex='7'>\n";
	foreach($sections_arr as $key=>$val) {
		if ($key == $section_id) { $sck = ' selected="selected"';}else{$sck = '';}
		$temp .= "<option name='ml_section_id' value='$key'$sck>".substr($val['section_label'],2,50)."</option>\n";
	}  
	$section_dd .= $temp . "</select>\n";
	
	
	// show form for new item
echo <<<eof

	 <form action='playlist_new.php' method='post' name='additem' onSubmit='return validate();'>
	 <input name='submit_via_button_flag' type='hidden' value='' />
	 <input name='show_id' type='hidden' value='$show_id' />
	 <input name='playlist_id' type='hidden' value='$playlist_id' />
	 <input name='post' type='hidden' value='yes' />
	 <input name='edit' type='hidden' value='$id' />
 <tr>
	<td class='tdgreen' align='center' ><h2><b>+</b></h2></td>
    <td class='tdgreen'>
	

    
<div id="wrapper">
<div id="content">
Artist (auto-fill)	:<br />
<div name='artist_unlocked' id='artist_unlocked'>
<input type="text" id="testinput_xml" class= "input_a"  style='border: 1px solid green;' name="dataa"  size='25' value="$artist" tabindex='1'>
</div>
<div name='artist_locked' id='artist_locked' class='lockedResponse' style='display:none; border: 1px solid green;'></div>
    <input name="testid" type="hidden" id="testid" value="$album_id" />

</div>
</div> 	
	

	
	</td>
    <td  class='tdgreen' >Album:<br />
<div name='album_unlocked' id='album_unlocked'>
<input name='album' type='text' id='album' size='25' class= 'input_a' style='border: 1px solid red;' tabindex='2' value="$album" onfocus="document.additem.testid.value=''"/>
</div>
<div name='album_locked' id='album_locked' class='lockedResponse' style='display:none; border: 1px solid red;'></div>
</td>
    <td class='tdgreen'>Song Title:<br />
<input name='song_title' type='text' size='25' id='song_title'  value="$track_name" tabindex='3'>
      </td>
    <td class='tdgreen' nowrap='nowrap'>
	<div name='area' id='area'>
	<table>
	<tr>
	<td class='small_inputs'><input name='playbox_p' type='checkbox' value='P' tabindex='4' $playbox_check/>Playbox&nbsp;
	<input name='playbox_p' type='checkbox' tabindex='5' value='L' $library_check/>Library&nbsp;
	<input name='playbox_p' type='checkbox' tabindex='5' value='B' $downstairs_check/>Downstairs
	<br>
	<input name='cancon_p' type='checkbox' value='Y' tabindex='6' $cancon_check/>Canadian</td>
	<td></td>
	</tr>
	<tr>
	<td class='small_inputs'>
	Genre $section_dd
	</td>
	</tr>
	</table>
	</div>
	</td>
	<td class='tdgreen'> &nbsp;&nbsp;Label  <input name='label' type='text' size='14' id='label' class='input_s' value="$label" tabindex='7'>&nbsp;&nbsp;  </td>
	<td class='tdgreen'><input name='$button' type='submit' value='$button' onClick='document.additem.submit_via_button_flag.value = "1"'/></td>
  </tr></form>

eof;
}  


function showFormSOCAN ($playlist_id,$show_id,$i,$arr,$sections_arr)  {
	
	$artist = $arr[$i][artist];
	$id = $arr[$i][id];
	//$category = $arr[$i][category]; if (!$category) $category = '2'; // default for blank 
	$section_id = $arr[$i][ml_section_id]; if (!$section_id || $section_id == 12) $section_id = 12;
	$cancon = $arr[$i][cancon]; if ($cancon) $cancon_check = "checked='checked'";
	$playbox = $arr[$i][playbox]; 
	if ($playbox == 'P') { $playbox_check = "checked='checked'"; } 
	if ($playbox == 'L') { $library_check = "checked='checked'"; }
	if ($playbox == 'B') { $downstairs_check = "checked='checked'"; }
	
	if ($arr[$i][theme_bg] == "T") $theme_checked = "selected='selected'";
	if ($arr[$i][theme_bg] == "B") $bg_checked = "selected='selected'";
	
	$label = $arr[$i][label];
	$track_name = $arr[$i][track_name];
	$album = $arr[$i][album];
	$album_id = $arr[$i][ml_album_id];
	$composer = $arr[$i][composer];
	$duration_minutes = $arr[$i][duration_minutes];
	$socan_time_played = $arr[$i][socan_time_played]; 
	
	if ($artist) { $button = "Save"; } else { $button = "Add"; }
	
	# BUILD SECTIONS drop-down
	$temp = "<select name='ml_section_id' class='small_inputs' style='background-color: green; color:white;' tabindex='7'>\n";
	foreach($sections_arr as $key=>$val) {
		if ($key == $section_id) { $sck = ' selected="selected"';}else{$sck = '';}
		$temp .= "<option name='ml_section_id' value='$key'$sck>".substr($val['section_label'],2,50)."</option>\n";
	}  
	$section_dd .= $temp . "</select>\n";
	
	
	// show form for new item
echo <<<eof

	 <form action='playlist_new.php' method='post' name='additem' onSubmit="return validate('socan');">
	 <input name='submit_via_button_flag' type='hidden' value='' />
	 <input name='show_id' type='hidden' value='$show_id' />
	 <input name='playlist_id' type='hidden' value='$playlist_id' />
	 <input name='post' type='hidden' value='yes' />
	 <input name='edit' type='hidden' value='$id' />
 <tr>
	<td class='tdgreen tdgreenER' align='center' ><h2><b>+</b></h2></td>
    <td class='tdgreen tdgreenER'>
	

    
<div id="wrapper">
<div id="content">
Artist (auto-fill)	:<br />
<div name='artist_unlocked' id='artist_unlocked'>
<input type="text" id="testinput_xml" class= "input_a"  style='border: 1px solid green;' name="dataa"  size='25' value="$artist" tabindex='1'>
</div>
<div name='artist_locked' id='artist_locked' class='lockedResponse' style='display:none; border: 1px solid green;'></div>
    <input name="testid" type="hidden" id="testid" value="$album_id" />

</div>
</div> 	
	

	
	</td>
    <td  class='tdgreen tdgreenER' >Album:<br />
<div name='album_unlocked' id='album_unlocked'>
<input name='album' type='text' id='album' size='25' class= 'input_a' style='border: 1px solid red;' tabindex='2' value="$album" onfocus="document.additem.testid.value=''"/>
</div>
<div name='album_locked' id='album_locked' class='lockedResponse' style='display:none; border: 1px solid red;'></div>
</td>
    <td class='tdgreen tdgreenER'>Song Title:<br />
<input name='song_title' type='text' size='25' id='song_title'  value="$track_name" tabindex='3'>
      </td>
    <td class='tdgreen tdgreenER' nowrap='nowrap'>
	<div name='area' id='area'>
	<table>
	<tr>
	<td class='small_inputs'><input name='playbox_p' type='checkbox' value='P' tabindex='4' $playbox_check/>Playbox&nbsp;
	<input name='playbox_p' type='checkbox' tabindex='5' value='L' $library_check/>Library&nbsp;
	<input name='playbox_p' type='checkbox' tabindex='5' value='B' $downstairs_check/>Downstairs
	<br>
	<input name='cancon_p' type='checkbox' value='Y' tabindex='6' $cancon_check/>Canadian</td>
	<td></td>
	</tr>
	<tr>
	<td class='small_inputs'>
	Genre $section_dd
	</td>
	</tr>
	</table>
	</div>
	</td>
	<td class='tdgreen tdgreenER'> &nbsp;&nbsp;Label  <input name='label' type='text' size='14' id='label' class='input_s' value="$label" tabindex='7'>&nbsp;&nbsp;  </td>
	<td class='tdgreen tdgreenER'></td>
  </tr>



<tr class='tdgreen tdgreenER'>
  <td colspan='2' style='text-align:center;border-top: 1px solid #fff;' ><strong>SOCAN Week:</strong><br>Please complete the following </td>
  <td  style='border-top: 1px solid #fff;'>Time played:<br><input name='socan_time_played' type='text' size='5' maxlength='5' id='socan_time_played' value="$socan_time_played" tabindex='10'> (hh:mm)  </td>
 
  <td  style='border-top: 1px solid #fff;'>Composer:<br><input name='composer' type='text' size='25' id='composer' value="$composer" tabindex='11'></td> 
  <td  style='border-top: 1px solid #fff;'>Theme/Background:
    <select name='theme_bg' tabindex='12'>
       <option value=''>--choose one--</option>
       <option value='T' $theme_checked>Theme</option>
       <option value='B' $bg_checked>Background</option> 
  </td> 
  <td  style='border-top: 1px solid #fff;'>Duration:<br><input name='duration_minutes' type='text' size='2' maxlength='2' id='duration_minutes' value="$duration_minutes" tabindex='13'>
<span style='font-size:9px;'>(minutes<br>-please round)</span>
  </td> 
  <td  style='border-top: 1px solid #fff;'><input name='$button' type='submit' value='$button' onClick='document.additem.submit_via_button_flag.value = "1"'/></td> 
</tr>
<hr>
</form>

eof;

// <td>Performer:<br><input name='performer' type='text' size='25' id='performer' value="" tabindex='10'></td>     

}


function showListing($arr,$show_id,$playlist_id,$bg,$order,$x,$i)  {

if ($arr[$i][ml_section_id]) {
	  $sec_cat = "Genre:<br>".substr ($arr[$i][section_label],2,50);
	}else{
	  $sec_cat = "Category:".$arr[$i][category];
	}

echo "
 <tr>
    <td bgcolor='$bg' align='center' >$order</td>
	<td bgcolor='$bg' ><strong>";
	echo ucwords ($arr[$i][artist])."</strong></td>
    <td bgcolor='$bg' ><strong>".ucwords ($arr[$i][album])."</strong></td>
    <td bgcolor='$bg' ><strong>".ucwords ($arr[$i][track_name])."</strong>
      </td>
	  <td bgcolor='$bg' >".$arr[$i][label]."
      </td>
    <td bgcolor='$bg' nowrap='nowrap'>
	<div id='area56' style='display: block; '>
	<table>
	<tr>
	<td class='small_inputs'>".$arr[$i][playbox]."<br>
	".$arr[$i][cancon]."</td>
	<td class='small_inputs'>$sec_cat </td>
	</tr></table>
	</div>
	</td>
	<td bgcolor='$bg' ><form name = 'del$x' id='del$x' onSubmit='return validateDel(del$x);' action='playlist_new.php?playlist_id=".$playlist_id."' method ='post'><input type='hidden' name='delete' value='".$arr[$i][id]."'><input type='hidden' name='show_id' value='$show_id'><input type='hidden' name='playlist_id' value='$playlist_id'><input name='Delete' type='submit' value='Delete' /></form>
	<div style='text-align:center;' class='editButton'><a href='playlist_new.php?mode=edit&playlist_id=".$playlist_id."&show_id=".$show_id."&item_id=".$arr[$i][id]."'>Edit</a></div>
	</td>
  </tr>

  ";	
	
} 

function showListingSOCAN($arr,$show_id,$playlist_id,$bg,$order,$x,$i)  {
 // this is called in addition to the above, creating a second row with socan fields

echo "
 <tr>
    <td bgcolor='$bg' ></td>
    
    <td colspan='6' bgcolor='$bg' >
     <div style='border: 1px solid #84E984;padding:3px; width:48%;'>
      	Composer: <strong>{$arr[$i][composer]}</strong> /
	  		Duration: <strong>{$arr[$i][duration_minutes]} min.</strong> /
	        Time Played: <strong>{$arr[$i][socan_time_played]}</strong>  / 
      		Theme/Background: <strong>{$arr[$i][theme_bg]}</strong>
    </div>
  </td> 
 </tr>

  ";	
	
}


?>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>    
